<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="打卡日期" prop="attendanceDate">
        <el-date-picker clearable
          v-model="queryParams.attendanceDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择打卡日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="打卡状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="打卡状态" clearable>
          <el-option label="正常" value="normal" />
          <el-option label="异常" value="abnormal" />
          <el-option label="未签退" value="no_out" />
          <el-option label="未签到" value="no_in" />
        </el-select>
      </el-form-item>
      <el-form-item label="打卡时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:attendance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:attendance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:attendance:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:attendance:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-s-flag"
          size="mini"
          @click="handleClockIn"
          v-hasPermi="['system:attendance:clock']"
        >签到</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-s-claim"
          size="mini"
          @click="handleClockOut"
          v-hasPermi="['system:attendance:clock']"
        >签退</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-setting"
          size="mini"
          @click="handleSettings"
          v-hasPermi="['system:attendance:edit']"
        >打卡设置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-info"
          size="mini"
          @click="showDebugInfo"
        >调试信息</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="打卡序号" align="center" prop="attendanceId" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="打卡日期" align="center" prop="attendanceDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.attendanceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到时间" align="center" prop="clockInTime">
        <template slot-scope="scope">
          <span>{{ scope.row.clockInTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到地点" align="center" prop="clockInLocation" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.clockInLocation }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签退时间" align="center" prop="clockOutTime">
        <template slot-scope="scope">
          <span>{{ scope.row.clockOutTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签退地点" align="center" prop="clockOutLocation" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.clockOutLocation }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.clockInTime && scope.row.clockOutTime" 
                 :type="isNormalAttendance(scope.row) ? 'success' : 'danger'" 
                 size="mini">
            {{ isNormalAttendance(scope.row) ? '正常' : '异常' }}
          </el-tag>
          <el-tag v-else-if="scope.row.clockInTime && !scope.row.clockOutTime" 
                 type="warning" 
                 size="mini">
            未签退
          </el-tag>
          <el-tag v-else 
                 type="info" 
                 size="mini">
            未签到
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:attendance:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:attendance:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工打卡记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="打卡日期" prop="attendanceDate">
          <el-date-picker clearable
            v-model="form.attendanceDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择打卡日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签到时间" prop="clockInTime">
          <el-time-picker
            v-model="form.clockInTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="请选择签到时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="签到地点" prop="clockInLocation">
          <el-input v-model="form.clockInLocation" placeholder="请输入签到地点" />
        </el-form-item>
        <el-form-item label="签退时间" prop="clockOutTime">
          <el-time-picker
            v-model="form.clockOutTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="请选择签退时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="签退地点" prop="clockOutLocation">
          <el-input v-model="form.clockOutLocation" placeholder="请输入签退地点" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_attendance_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 签到对话框 -->
    <el-dialog title="签到" :visible.sync="clockInOpen" width="500px" append-to-body>
      <el-form ref="clockInForm" :model="clockInForm" :rules="clockInRules" label-width="80px">
        <el-form-item label="签到地点" prop="clockInLocation">
          <el-input v-model="clockInForm.clockInLocation" placeholder="请输入签到地点" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="clockInForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClockIn">确 定</el-button>
        <el-button @click="cancelClockIn">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 签退对话框 -->
    <el-dialog title="签退" :visible.sync="clockOutOpen" width="500px" append-to-body>
      <el-form ref="clockOutForm" :model="clockOutForm" :rules="clockOutRules" label-width="80px">
        <el-form-item label="签退地点" prop="clockOutLocation">
          <el-input v-model="clockOutForm.clockOutLocation" placeholder="请输入签退地点" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="clockOutForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClockOut">确 定</el-button>
        <el-button @click="cancelClockOut">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打卡设置对话框 -->
    <el-dialog title="打卡设置" :visible.sync="settingsOpen" width="500px" append-to-body>
      <el-form ref="settingsForm" :model="settingsForm" label-width="120px">
        <el-form-item label="正常签到时间" prop="clockInTime">
          <el-time-picker
            v-model="settingsForm.clockInTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="请选择签到时间">
          </el-time-picker>
          <div class="el-form-item-description">签到时间不晚于此时间视为正常</div>
        </el-form-item>
        <el-form-item label="正常签退时间" prop="clockOutTime">
          <el-time-picker
            v-model="settingsForm.clockOutTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="请选择签退时间">
          </el-time-picker>
          <div class="el-form-item-description">签退时间不早于此时间视为正常</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSettings">确 定</el-button>
        <el-button @click="cancelSettings">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 补卡申请对话框 -->
    <!-- 已移除补卡申请对话框 -->

    <!-- 请假申请对话框 -->
    <!-- 已移除请假申请对话框 -->
  </div>
</template>

<script>
import { listAttendance, getAttendance, delAttendance, addAttendance, updateAttendance, clockIn, clockOut, getTodayStatus, updateAttendanceSettings, getAttendanceSettings } from "@/api/system/attendance";
import { parseTime, addDateRange } from "@/utils/ruoyi";

export default {
  name: "Attendance",
  dicts: ['sys_attendance_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工打卡记录表格数据
      attendanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示签到弹出层
      clockInOpen: false,
      // 是否显示签退弹出层
      clockOutOpen: false,
      // 是否显示打卡设置弹出层
      settingsOpen: false,
      // 打卡设置表单
      settingsForm: {
        clockInTime: '09:00:00',
        clockOutTime: '18:00:00'
      },
      // 日期范围
      dateRange: [],
      // 今日打卡状态
      todayStatus: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        deptName: null,
        attendanceDate: null,
        clockInTime: null,
        clockInLocation: null,
        clockOutTime: null,
        clockOutLocation: null,
        status: null
      },
      // 表单参数
      form: {},
      // 签到表单参数
      clockInForm: {
        clockInLocation: "",
        remark: ""
      },
      // 签退表单参数
      clockOutForm: {
        clockOutLocation: "",
        remark: ""
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        attendanceDate: [
          { required: true, message: "打卡日期不能为空", trigger: "blur" }
        ]
      },
      // 签到表单校验
      clockInRules: {
        clockInLocation: [
          { required: true, message: "签到地点不能为空", trigger: "blur" }
        ]
      },
      // 签退表单校验
      clockOutRules: {
        clockOutLocation: [
          { required: true, message: "签退地点不能为空", trigger: "blur" }
        ]
      },
      // 是否为管理员
      isAdmin: false
    };
  },
  created() {
    this.getList();
    // 获取今日打卡状态
    this.getTodayAttendanceStatus().then(data => {
      this.todayStatus = data;
    }).catch(() => {
      // 错误已在方法中处理
    });
    
    // 获取考勤设置
    this.getAttendanceSettings();
    
    // 检查当前用户是否为管理员
    this.checkIsAdmin();
  },
  methods: {
    /** 查询员工打卡记录列表 */
    getList() {
      this.loading = true;
      
      // 先获取考勤设置，再获取打卡记录列表
      this.getAttendanceSettings().then(() => {
        // 创建查询参数的副本，移除状态条件（我们会在前端处理）
        const queryParams = { ...this.queryParams };
        const status = queryParams.status;
        delete queryParams.status;
        
        // 获取考勤记录
        listAttendance(this.addDateRange(queryParams, this.dateRange)).then(response => {
          // 获取列表数据
          let attendanceData = response.rows || [];
          
          // 如果有状态筛选条件，则根据状态判断逻辑进行筛选
          if (status) {
            attendanceData = attendanceData.filter(item => {
              const hasClockIn = !!item.clockInTime;
              const hasClockOut = !!item.clockOutTime;
              
              switch (status) {
                case 'normal':
                  return hasClockIn && hasClockOut && this.isNormalAttendance(item);
                case 'abnormal':
                  return hasClockIn && hasClockOut && !this.isNormalAttendance(item);
                case 'no_out':
                  return hasClockIn && !hasClockOut;
                case 'no_in':
                  return !hasClockIn;
                default:
                  return true;
              }
            });
          }
          
          // 只显示普通考勤记录，过滤掉补卡和请假记录
          attendanceData = attendanceData.filter(item => 
            item.status !== 'R' && item.status !== 'L'
          );
          
          this.attendanceList = attendanceData;
          this.total = attendanceData.length;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 获取今日打卡状态 */
    getTodayAttendanceStatus() {
      return new Promise((resolve, reject) => {
        getTodayStatus().then(response => {
          if (response.code === 200) {
            resolve(response.data);
          } else {
            this.$modal.msgError(response.msg || "获取今日打卡状态失败");
            reject(new Error(response.msg || "获取今日打卡状态失败"));
          }
        }).catch(error => {
          console.error("获取今日打卡状态失败:", error);
          this.$modal.msgError("获取今日打卡状态失败，请稍后再试");
          reject(error);
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消签到
    cancelClockIn() {
      this.clockInOpen = false;
      this.resetClockInForm();
    },
    // 取消签退
    cancelClockOut() {
      this.clockOutOpen = false;
      this.resetClockOutForm();
    },
    // 取消打卡设置
    cancelSettings() {
      this.settingsOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        attendanceId: null,
        userId: null,
        attendanceDate: null,
        clockInTime: null,
        clockInLocation: null,
        clockOutTime: null,
        clockOutLocation: null,
        status: "0",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 签到表单重置
    resetClockInForm() {
      this.clockInForm = {
        clockInLocation: "",
        remark: ""
      };
      this.resetForm("clockInForm");
    },
    // 签退表单重置
    resetClockOutForm() {
      this.clockOutForm = {
        clockOutLocation: "",
        remark: ""
      };
      this.resetForm("clockOutForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.attendanceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加员工打卡记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const attendanceId = row.attendanceId || this.ids[0]
      getAttendance(attendanceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改员工打卡记录";
      });
    },
    /** 签到按钮操作 */
    handleClockIn() {
      // 先刷新今日打卡状态
      this.getTodayAttendanceStatus().then(todayData => {
        this.todayStatus = todayData;
        if (todayData && todayData.clockInTime) {
          this.$modal.msgError("今天已经签到，不能重复签到");
          return;
        }
        this.resetClockInForm();
        this.clockInOpen = true;
      }).catch(() => {
        // 错误已在 getTodayAttendanceStatus 中处理
      });
    },
    /** 签退按钮操作 */
    handleClockOut() {
      // 先刷新今日打卡状态
      this.getTodayAttendanceStatus().then(todayData => {
        this.todayStatus = todayData;
        if (!todayData || !todayData.clockInTime) {
          this.$modal.msgError("今天还未签到，请先签到");
          return;
        }
        if (todayData.clockOutTime) {
          this.$modal.msgError("今天已经签退，不能重复签退");
          return;
        }
        this.resetClockOutForm();
        this.clockOutOpen = true;
      }).catch(() => {
        // 错误已在 getTodayAttendanceStatus 中处理
      });
    },
    /** 打卡设置按钮操作 */
    handleSettings() {
      this.getAttendanceSettings();
      this.settingsOpen = true;
    },
    /** 获取考勤设置 */
    getAttendanceSettings() {
      return new Promise((resolve, reject) => {
        import("@/api/system/attendance").then(module => {
          const { getAttendanceSettings } = module;
          getAttendanceSettings().then(response => {
            if (response.code === 200) {
              this.settingsForm.clockInTime = response.data.clockInTime;
              this.settingsForm.clockOutTime = response.data.clockOutTime;
              resolve(response.data);
            } else {
              this.$modal.msgError(response.msg || "获取考勤设置失败");
              reject(new Error(response.msg || "获取考勤设置失败"));
            }
          }).catch(error => {
            console.error("获取考勤设置失败:", error);
            this.$modal.msgError("获取考勤设置失败，请稍后再试");
            reject(error);
          });
        });
      });
    },
    /** 提交签到按钮 */
    submitClockIn() {
      this.$refs["clockInForm"].validate(valid => {
        if (valid) {
          clockIn(this.clockInForm).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("签到成功");
              this.clockInOpen = false;
              // 刷新数据
              this.getList();
              // 添加短暂延迟，确保后端数据已更新
              setTimeout(() => {
                this.getTodayAttendanceStatus().then(data => {
                  this.todayStatus = data;
                }).catch(() => {
                  // 错误已在方法中处理
                });
              }, 500);
            } else {
              this.$modal.msgError(response.msg || "签到失败");
            }
          }).catch(error => {
            console.error("签到失败:", error);
            this.$modal.msgError("签到失败，请稍后再试");
          });
        }
      });
    },
    /** 提交签退按钮 */
    submitClockOut() {
      this.$refs["clockOutForm"].validate(valid => {
        if (valid) {
          clockOut(this.clockOutForm).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("签退成功");
              this.clockOutOpen = false;
              // 刷新数据
              this.getList();
              // 添加短暂延迟，确保后端数据已更新
              setTimeout(() => {
                this.getTodayAttendanceStatus().then(data => {
                  this.todayStatus = data;
                }).catch(() => {
                  // 错误已在方法中处理
                });
              }, 500);
            } else {
              this.$modal.msgError(response.msg || "签退失败");
            }
          }).catch(error => {
            console.error("签退失败:", error);
            this.$modal.msgError("签退失败，请稍后再试");
          });
        }
      });
    },
    /** 提交打卡设置 */
    submitSettings() {
      this.$refs["settingsForm"].validate(valid => {
        if (valid) {
          updateAttendanceSettings(this.settingsForm).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("设置成功");
              this.settingsOpen = false;
            } else {
              this.$modal.msgError(response.msg || "设置失败");
            }
          }).catch(error => {
            console.error("设置失败:", error);
            this.$modal.msgError("设置失败，请稍后再试");
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.attendanceId != null) {
            updateAttendance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttendance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attendanceIds = row.attendanceId || this.ids;
      
      // 处理普通考勤记录
      this.$modal.confirm('是否确认删除员工打卡记录编号为"' + attendanceIds + '"的数据项?').then(function() {
        return delAttendance(attendanceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/attendance/export', {
        ...this.queryParams
      }, `attendance_${new Date().getTime()}.xlsx`)
    },
    /** 判断打卡是否正常 */
    isNormalAttendance(row) {
      // 如果没有签到或签退记录，直接返回false
      if (!row.clockInTime || !row.clockOutTime) {
        return false;
      }
      
      // 获取打卡设置的时间
      const standardInTime = this.settingsForm.clockInTime || '09:00:00';
      const standardOutTime = this.settingsForm.clockOutTime || '18:00:00';
      
      // 转换为秒进行比较
      const clockInSeconds = this.timeToSeconds(row.clockInTime);
      const clockOutSeconds = this.timeToSeconds(row.clockOutTime);
      const standardInSeconds = this.timeToSeconds(standardInTime);
      const standardOutSeconds = this.timeToSeconds(standardOutTime);
      
      // 判断是否正常打卡：签到时间不晚于标准签到时间，签退时间不早于标准签退时间
      const isNormalIn = clockInSeconds <= standardInSeconds;
      const isNormalOut = clockOutSeconds >= standardOutSeconds;
      
      return isNormalIn && isNormalOut;
    },
    
    /** 时间转换为秒 */
    timeToSeconds(timeStr) {
      if (!timeStr) return 0;
      const [hours, minutes, seconds] = timeStr.split(':').map(Number);
      return hours * 3600 + minutes * 60 + seconds;
    },
    // 补卡申请按钮操作
    handleReapply() {
      this.reapplyOpen = true;
    },
    // 提交补卡申请
    submitReapply() {
      this.$refs["reapplyForm"].validate(valid => {
        if (valid) {
          // 处理补卡逻辑
          const data = {
            attendanceDate: this.reapplyForm.attendanceDate,
            reapplyType: this.reapplyForm.reapplyType,
            reapplyTime: this.reapplyForm.reapplyTime,
            reapplyLocation: this.reapplyForm.reapplyLocation,
            reason: this.reapplyForm.reason
          };
          
          applyReapply(data).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("补卡申请提交成功");
              this.reapplyOpen = false;
              // 重置表单
              this.reapplyForm = {
                attendanceDate: null,
                reapplyType: null,
                reapplyTime: null,
                reapplyLocation: null,
                reason: null
              };
              // 刷新列表
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "补卡申请提交失败");
            }
          }).catch(error => {
            console.error("补卡申请提交失败:", error);
            this.$modal.msgError("补卡申请提交失败，请稍后再试");
          });
        }
      });
    },
    // 取消补卡申请
    cancelReapply() {
      this.reapplyOpen = false;
    },
    // 请假申请按钮操作
    handleLeave() {
      this.leaveOpen = true;
    },
    // 提交请假申请
    submitLeave() {
      this.$refs["leaveForm"].validate(valid => {
        if (valid) {
          // 处理请假逻辑
          const data = {
            leaveType: this.leaveForm.leaveType,
            startTime: this.leaveForm.startTime,
            endTime: this.leaveForm.endTime,
            reason: this.leaveForm.reason
          };
          
          applyLeave(data).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("请假申请提交成功");
              this.leaveOpen = false;
              // 重置表单
              this.leaveForm = {
                leaveType: null,
                startTime: null,
                endTime: null,
                reason: null
              };
              // 刷新列表
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "请假申请提交失败");
            }
          }).catch(error => {
            console.error("请假申请提交失败:", error);
            this.$modal.msgError("请假申请提交失败，请稍后再试");
          });
        }
      });
    },
    // 取消请假申请
    cancelLeave() {
      this.leaveOpen = false;
    },
    // 格式化日期，仅保留年月日
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    // 查看补卡申请详情
    viewReapplyDetail(row) {
      if (row.reapplyInfo) {
        // 显示补卡申请详情
        const reapplyInfo = row.reapplyInfo;
        const content = `
          <div style="padding: 10px;">
            <p><strong>补卡类型：</strong>${reapplyInfo.reapplyType === 'in' ? '签到补卡' : '签退补卡'}</p>
            <p><strong>补卡时间：</strong>${reapplyInfo.reapplyTime}</p>
            <p><strong>补卡地点：</strong>${reapplyInfo.reapplyLocation}</p>
            <p><strong>补卡原因：</strong>${reapplyInfo.reason || '无'}</p>
            <p><strong>申请状态：</strong>${this.getReapplyStatusText(reapplyInfo.status)}</p>
            <p><strong>申请时间：</strong>${this.parseTime(reapplyInfo.createTime)}</p>
          </div>
        `;
        this.$alert(content, '补卡申请详情', {
          dangerouslyUseHTMLString: true,
          closeOnClickModal: true,
          confirmButtonText: '关闭'
        });
      }
    },
    
    // 获取补卡申请状态文本
    getReapplyStatusText(status) {
      switch(status) {
        case '0': return '待审批';
        case '1': return '已通过';
        case '2': return '已驳回';
        default: return '未知';
      }
    },
    // 删除补卡申请记录
    handleDeleteReapply(row) {
      if (row.reapplyInfo) {
        const reapplyId = row.reapplyInfo.reapplyId;
        console.log("删除补卡申请ID:", reapplyId);
        this.$modal.confirm('是否确认删除该补卡申请记录?').then(() => {
          return deleteReapply(reapplyId);
        }).then(response => {
          console.log("删除补卡申请成功:", response);
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(error => {
          console.error("删除补卡申请失败:", error);
          this.$modal.msgError("删除失败: " + (error.message || "未知错误"));
        });
      } else if (row.attendanceId && typeof row.attendanceId === 'string' && row.attendanceId.startsWith('R')) {
        // 如果没有reapplyInfo但有R开头的ID，尝试从ID中提取
        const reapplyId = parseInt(row.attendanceId.substring(1));
        if (isNaN(reapplyId)) {
          console.error("无法解析补卡申请ID:", row.attendanceId);
          this.$modal.msgError("无法解析补卡申请ID");
          return;
        }
        console.log("从attendanceId提取的补卡申请ID:", reapplyId);
        this.$modal.confirm('是否确认删除该补卡申请记录?').then(() => {
          return deleteReapply(reapplyId);
        }).then(response => {
          console.log("删除补卡申请成功:", response);
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(error => {
          console.error("删除补卡申请失败:", error);
          this.$modal.msgError("删除失败: " + (error.message || "未知错误"));
        });
      } else {
        console.error("无法获取补卡申请ID:", row);
        this.$modal.msgError("无法获取补卡申请ID");
      }
    },
    // 获取审批状态文本
    getApprovalStatusText(status) {
      switch(status) {
        case '0': return '待审批';
        case '1': return '已通过';
        case '2': return '已驳回';
        default: return '未知';
      }
    },
    // 获取审批标签类型
    getApprovalTagType(status) {
      switch(status) {
        case '0': return 'warning';
        case '1': return 'success';
        case '2': return 'danger';
        default: return 'info';
      }
    },
    // 审批补卡申请
    handleApproveReapply(row, status) {
      console.log("审批补卡申请:", row, "状态:", status);
      
      // 检查是否有reapplyInfo
      if (!row.reapplyInfo) {
        console.error("没有找到补卡申请信息:", row);
        
        // 尝试从attendanceId中提取reapplyId
        if (row.attendanceId && typeof row.attendanceId === 'string' && row.attendanceId.startsWith('R')) {
          const reapplyId = parseInt(row.attendanceId.substring(1));
          if (!isNaN(reapplyId)) {
            console.log("从attendanceId提取的补卡申请ID:", reapplyId);
            
            const data = {
              status: status,
              remark: status === '1' ? '审批通过' : '审批驳回'
            };
            
            this.$modal.confirm(`是否确认${status === '1' ? '通过' : '驳回'}该补卡申请?`).then(() => {
              return approveReapply(reapplyId, data);
            }).then(response => {
              console.log("审批响应:", response);
              if (response.code === 200) {
                this.$modal.msgSuccess("审批成功");
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "审批失败");
              }
            }).catch(error => {
              console.error("审批失败:", error);
              console.error("错误详情:", error.response ? error.response.data : "无响应数据");
              this.$modal.msgError("审批失败: " + (error.message || "未知错误"));
            });
          } else {
            this.$modal.msgError("无法解析补卡申请ID");
          }
        } else {
          this.$modal.msgError("无法获取补卡申请信息");
        }
        return;
      }
      
      const reapplyId = row.reapplyInfo.reapplyId;
      console.log("补卡申请ID:", reapplyId);
      
      const data = {
        status: status,
        remark: status === '1' ? '审批通过' : '审批驳回'
      };
      
      this.$modal.confirm(`是否确认${status === '1' ? '通过' : '驳回'}该补卡申请?`).then(() => {
        return approveReapply(reapplyId, data);
      }).then(response => {
        console.log("审批响应:", response);
        if (response.code === 200) {
          this.$modal.msgSuccess("审批成功");
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "审批失败");
        }
      }).catch(error => {
        console.error("审批失败:", error);
        console.error("错误详情:", error.response ? error.response.data : "无响应数据");
        this.$modal.msgError("审批失败: " + (error.message || "未知错误"));
      });
    },
    // 审批请假申请
    handleApproveLeave(row, status) {
      console.log("审批请假申请:", row, "状态:", status);
      
      // 检查是否有leaveInfo
      if (!row.leaveInfo) {
        console.error("没有找到请假申请信息:", row);
        
        // 尝试从attendanceId中提取leaveId
        if (row.attendanceId && typeof row.attendanceId === 'string' && row.attendanceId.startsWith('L')) {
          const leaveId = parseInt(row.attendanceId.substring(1));
          if (!isNaN(leaveId)) {
            console.log("从attendanceId提取的请假申请ID:", leaveId);
            
            const data = {
              status: status,
              remark: status === '1' ? '审批通过' : '审批驳回'
            };
            
            this.$modal.confirm(`是否确认${status === '1' ? '通过' : '驳回'}该请假申请?`).then(() => {
              return approveLeave(leaveId, data);
            }).then(response => {
              console.log("审批响应:", response);
              if (response.code === 200) {
                this.$modal.msgSuccess("审批成功");
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "审批失败");
              }
            }).catch(error => {
              console.error("审批失败:", error);
              console.error("错误详情:", error.response ? error.response.data : "无响应数据");
              this.$modal.msgError("审批失败: " + (error.message || "未知错误"));
            });
          } else {
            this.$modal.msgError("无法解析请假申请ID");
          }
        } else {
          this.$modal.msgError("无法获取请假申请信息");
        }
        return;
      }
      
      const leaveId = row.leaveInfo.leaveId;
      console.log("请假申请ID:", leaveId);
      
      const data = {
        status: status,
        remark: status === '1' ? '审批通过' : '审批驳回'
      };
      
      this.$modal.confirm(`是否确认${status === '1' ? '通过' : '驳回'}该请假申请?`).then(() => {
        return approveLeave(leaveId, data);
      }).then(response => {
        console.log("审批响应:", response);
        if (response.code === 200) {
          this.$modal.msgSuccess("审批成功");
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "审批失败");
        }
      }).catch(error => {
        console.error("审批失败:", error);
        console.error("错误详情:", error.response ? error.response.data : "无响应数据");
        this.$modal.msgError("审批失败: " + (error.message || "未知错误"));
      });
    },
    // 查看请假详情
    viewLeaveDetail(row) {
      if (row.leaveInfo) {
        // 显示请假详情
        const leaveInfo = row.leaveInfo;
        const content = `
          <div style="padding: 10px;">
            <p><strong>请假类型：</strong>${leaveInfo.leaveType}</p>
            <p><strong>开始时间：</strong>${this.parseTime(leaveInfo.startTime)}</p>
            <p><strong>结束时间：</strong>${this.parseTime(leaveInfo.endTime)}</p>
            <p><strong>请假原因：</strong>${leaveInfo.reason || '无'}</p>
            <p><strong>申请状态：</strong>${this.getApprovalStatusText(leaveInfo.status)}</p>
            <p><strong>申请时间：</strong>${this.parseTime(leaveInfo.createTime)}</p>
          </div>
        `;
        this.$alert(content, '请假详情', {
          dangerouslyUseHTMLString: true,
          closeOnClickModal: true,
          confirmButtonText: '关闭'
        });
      }
    },
    // 删除请假记录
    handleDeleteLeave(row) {
      if (row.leaveInfo) {
        const leaveId = row.leaveInfo.leaveId;
        console.log("删除请假ID:", leaveId);
        this.$modal.confirm('是否确认删除该请假记录?').then(() => {
          return deleteLeave(leaveId);
        }).then(response => {
          console.log("删除请假成功:", response);
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(error => {
          console.error("删除请假失败:", error);
          this.$modal.msgError("删除失败: " + (error.message || "未知错误"));
        });
      } else if (row.attendanceId && typeof row.attendanceId === 'string' && row.attendanceId.startsWith('L')) {
        // 如果没有leaveInfo但有L开头的ID，尝试从ID中提取
        const leaveId = parseInt(row.attendanceId.substring(1));
        if (isNaN(leaveId)) {
          console.error("无法解析请假ID:", row.attendanceId);
          this.$modal.msgError("无法解析请假ID");
          return;
        }
        console.log("从attendanceId提取的请假ID:", leaveId);
        this.$modal.confirm('是否确认删除该请假记录?').then(() => {
          return deleteLeave(leaveId);
        }).then(response => {
          console.log("删除请假成功:", response);
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(error => {
          console.error("删除请假失败:", error);
          this.$modal.msgError("删除失败: " + (error.message || "未知错误"));
        });
      } else {
        console.error("无法获取请假ID:", row);
        this.$modal.msgError("无法获取请假ID");
      }
    },
    // 检查当前用户是否为管理员
    checkIsAdmin() {
      // 从用户信息中获取角色
      const userInfo = this.$store.getters.user || {};
      const roles = userInfo.roles || [];
      
      // 更宽松的管理员检查 - 任何包含admin的角色或拥有考勤管理权限的用户
      this.isAdmin = roles.some(role => 
        role.roleKey === 'admin' || 
        role.roleKey === 'administrator' || 
        role.roleKey.includes('admin') ||
        role.permissions && role.permissions.some(p => p.includes('system:attendance:edit'))
      );
      
      // 调试信息
      console.log("当前用户:", userInfo);
      console.log("用户角色:", roles);
      console.log("是否管理员:", this.isAdmin);
      
      // 临时设置为true以测试
      this.isAdmin = true;
    },
    // 显示调试信息
    showDebugInfo() {
      console.log("当前加载的所有记录:", this.attendanceList);
      
      // 检查isAdmin状态
      console.log("isAdmin:", this.isAdmin);
      
      // 显示调试信息
      const debugInfo = `
        总记录数: ${this.attendanceList.length}
        isAdmin: ${this.isAdmin}
      `;
      
      this.$alert(debugInfo, '调试信息', {
        confirmButtonText: '关闭'
      });
    }
  }
};
</script>

<style scoped>
.el-form-item-description {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 